// packageH/circleCommunity/circlereleaseVideo/circlereleaseVideo.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",
    myvideo: "",
    goods_id: "",
    title: "",
    videoUrl: "",
    isVideo: true,
    realVideo: "",
    coverUrl: "",
    duration: 0, //视频时长
    chooseGoods: null, //商品信息
    videoPath: "", //视频链接参数
    videoCover: "", //封面图片参数
    limit: 60, //视频限制时长
    uploadIng: false, //正在上传中
    videoProgress: 0,
    showUploadBtn: false, //是否显示确认上传按钮引导用户上传（解决ios无法自动播放）
    imguploadIng: false,
    isNeedGoods: true, //是否开启选择商品

    circleId: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.circleId = options.circleId;
    this.data.myvideo = wx.createVideoContext("myvideo");
    this.init();
    this.getList();
    //this.getPermission();
    try {
      var value = wx.getStorageSync("shareVideoPath");
      if (value) {
        let shareVideoPath = JSON.parse(value);
        if (shareVideoPath.title) {
          this.setData({
            title: shareVideoPath.title,
          });
        }
        if (shareVideoPath.videoUrl) {
          this.setData({
            videoUrl: shareVideoPath.videoUrl,
          });
        }
        if (shareVideoPath.videoUrl) {
          this.setData({
            videoUrl: shareVideoPath.videoUrl,
            videoPath: shareVideoPath.videoUrl,
          });
        }
        if (shareVideoPath.videoCover) {
          this.setData({
            videoCover: shareVideoPath.videoCover,
          });
        }
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  setGoodsId(goods_id) {
    if (goods_id) {
      this.setData({
        goods_id,
      });
      this.getGoodsById();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareTimeline(){},
  onShareAppMessage: function () {},
  init() {
    this.setData({
      title: "",
      videoUrl: "",
      isVideo: true,
      duration: 0,
      chooseGoods: null,
      videoCover: "",
      limit: "",
      uploadIng: false,
      showUploadBtn: false,
      coverUrl: "",
      realVideo: "",
      videoPath: "",
      isNeedGoods: true,
    });
  },
  getList() {
    //获取限制时长
    let urlStr = app.getNetAddresss("plugin.circle.frontend.circle.get-set");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            isNeedGoods: res.data.select_goods == 1 ? true : false,
          });
          if (!app._isTextEmpty(res.data.limit)) {
            this.setData({
              limit: res.data.limit,
            });
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //验证会员发布权限
  getPermission() {
    //  let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.permission.verify");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (!res.data.ret) {
            wx.navigateBack({
              delta: 1,
              success: () => {
                setTimeout(() => {
                  wx.showToast({
                    title: res.msg,
                    icon: "none",
                    duration: 1500,
                  });
                }, 1000);
              },
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getGoodsById() {
    let that = this;
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._getNetWork({
      url: urlStr,
      data: {
        id: Number(this.data.goods_id),
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            chooseGoods: res.data.get_goods,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  beforeUpVideo(evt) {
    console.log("开始上传前", evt);
    this.data.realVideo = evt.detail;
    this.setData({
      uploadIng: true,
    });
  },
  successUpVideo(resData) {
    console.log("上传成功后", resData);
    // var resData = evt.detail.res;
    if (resData.result == 1) {
      this.setData({
        uploadIng: false,
        videoPath: resData.data.img_url,
        videoUrl: resData.data.img_url,
      });
      //本地保存标题、视频链接--------------
      let hasData = {
        title: this.data.title ? this.data.title : "",
        videoUrl: this.data.videoPath ? this.data.videoPath : "",
        videoCover: this.data.videoCover ? this.data.videoCover : "",
      };
      wx.setStorageSync("shareVideoPath", JSON.stringify(hasData));
    } else {
      this.setData({
        videoUrl: null,
        isVideo: true,
        duration: 0,
        videoCover: "",
        uploadIng: false,
        showUploadBtn: false,
      });
      app.tips(resData.msg);
    }
  },

  deleteImg(evt) {
    console.log(evt);
    this.data.videoCover = "";
    let hasData = {
      title: this.data.title ? this.data.title : "",
      videoUrl: this.data.videoPath ? this.data.videoPath : "",
      videoCover: this.data.videoCover ? this.data.videoCover : "",
    };
    wx.setStorageSync("shareVideoPath", JSON.stringify(hasData));
  },
  beforeUpImg() {
    this.setData({
      imguploadIng: true,
    });
  },
  successUpImg(evt) {
    console.log(evt.detail.res);
    var resData = evt.detail.res;
    if (resData.result == 1) {
      this.setData({
        videoCover: resData.data.img_url,
      });
      //本地保存标题、视频链接--------------
      let hasData = {
        title: this.data.title ? this.data.title : "",
        videoUrl: this.data.videoPath ? this.data.videoPath : "",
        videoCover: this.data.videoCover ? this.data.videoCover : "",
      };
      wx.setStorageSync("shareVideoPath", JSON.stringify(hasData));
      this.setData({
        imguploadIng: false,
      });
    } else {
      this.setData({
        imguploadIng: false,
      });
      app.tips(resData.msg);
    }
  },

  BtnMethos() {
    let that = this;
    if (this.data.isNeedGoods && app._isTextEmpty(this.data.chooseGoods)) {
      //商品为空，则跳转到商品搜索页添加商品
      //本地保存标题、视频链接--------------
      let hasData = {
        title: that.data.title ? that.data.title : "",
        videoUrl: that.data.videoPath ? that.data.videoPath : "",
        videoCover: that.data.videoCover ? that.data.videoCover : "",
      };
      wx.setStorageSync("shareVideoPath", JSON.stringify(hasData));
      wx.navigateTo({
        url: "/packageH/circleCommunity/circleVideogood/circleVideogood",
      });
    } else {
      //商品不为空，而且视频、标题已添加，则进行发布
      if (app._isTextEmpty(this.data.title)) {
        wx.showToast({
          title: "请输入4-18个字标题",
          icon: "none",
          duration: 1500,
        });
        return;
      }
      if (app._isTextEmpty(this.data.videoUrl)) {
        wx.showToast({
          title: "请选择视频进行上传！",
          icon: "none",
          duration: 1500,
        });
        return;
      }
      if (app._isTextEmpty(this.data.videoCover)) {
        wx.showToast({
          title: "请选择一张图片作为视频封面图！",
          icon: "none",
          duration: 1500,
        });
        return;
      }
      let json = {
        goods_id: this.data.goods_id,
        title: this.data.title,
        content: this.data.videoPath,
        img: this.data.videoCover,
        circle_id: this.data.circleId,
        invitation_status: 2,

        address: "",
        store_id: "",
        city: "",
        latitude: "",
        longitude: "",
        ylat: "",
        ylng: "",
      };
      let urlStr = app.getNetAddresss("plugin.circle.frontend.circle-invitation.release");
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
            try {
              wx.removeStorageSync("shareVideoPath");
            } catch (e) {
              // Do something when catch error
            }
            wx.navigateBack({
              delta: 2,
            });
            // wx.navigateTo({
            // 	url: '/packageC/video_goods/VideoList/VideoList'
            // })
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  titleBlur(event) {
    let val = event.detail.value;
    if (val.length < 4) {
      wx.showToast({
        icon: "none",
        title: "请输入不小于4个字",
        duration: 1500,
      });
      return;
    }
    this.setData({
      title: val,
    });
  },
  gotoAdd() {
    wx.navigateTo({
      url: "/packageH/circleCommunity/circleVideogood/circleVideogood",
    });
  },
  onReadVideo() {
    //iOS中选择上传视频不能超过60秒
    wx.chooseVideo({
      sourceType: ["album", "camera"],
      maxDuration: 60,
      camera: "back",
      success: (res) => {
        this.getDuration(res.duration, res.tempFilePath);
      },
    });
  },
  getDuration(durationData, videoData) {
    let duration = durationData;

    //获取视频或者音频时长
    this.data.duration = duration;
    console.log("视频时长：", this.data.duration, this.data.limit + 1, this.data.limit && this.data.duration > this.data.limit + 1);
    if (this.data.duration < 1) {
      this.setData({
        videoUrl: null,
      });
      return app.tips("视频时长太短了！");
    } else if (this.data.limit != 0 && this.data.duration > parseInt(this.data.limit) + 1) {
      this.setData({
        videoUrl: null,
      });
      return app.tips(`视频时长不能超过${this.data.limit}秒`);
    } else {
      this.setData({
        videoUrl: videoData,
      });
      this.setSrcAndCaptureImage(videoData);
      return;
    }
  },
  setSrcAndCaptureImage(videoData) {
    this.beforeUpVideo(videoData)
    this.uploadAudioM(videoData); //上传视频 
  },
  uploadAudioM(videoData) {
    let urlStr = app.getNetAddresss("upload.uploadPic");
    urlStr += "&upload_type=video";
    wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: videoData,
      name: "file",
      formData: {},
      success:(resdata)=> {
        let res = JSON.parse(resdata.data);
        if(res.result!=1){
          this.setData({videoUrl:null});
        }
        this.successUpVideo(res)
      },
    });
  },
  clearVideo(){
    this.setData({
      videoUrl:null
    })
    if(wx.getStorageSync('shareVideoPath')){
      wx.clearStorageSync("shareVideoPath");
    }
  },
});
